import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'

Vue.use(Vuex)
const myPlugin = store => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    window.localStorage.setItem('cartlist',JSON.stringify(state.cartlist))
    window.localStorage.setItem('amount',JSON.stringify(state.amount))
    window.localStorage.setItem('user',JSON.stringify(state.user))
  })
}
const jihe=()=>{
  state.amount=state.cartlist.reduce((result,item)=>{
    result=result+item.count
    return result
  },0)
}

const store = new Vuex.Store({
  state,
  mutations:{toggleCityPickerVisible (state) {
    state.cityPickerVisible = !state.cityPickerVisible
  },
  changeCurrentAddress (state, address) {
    state.addressProvince = address[0]
    state.addressCity = address[1]
    state.user.address=state.addressCity
  },
    remove(state,id){
      state.cartlist=state.cartlist.filter(item=>item.classifyId!==id)
      jihe()
    },     
    addtocart(state,list){   
      const has=state.cartlist.some(item=>item===list)
      if(has){       
         state.cartlist.map(item=>{
           if(item===list){
             item.count=item.count+1}          
          return item
        })       
      }
      else{
        state.cartlist.push(list) 
      } 
      jihe();     
    },
    jian(state,id){
      state.cartlist=state.cartlist.map(item=>{
      if(id===item.classifyId){
        item.count--
        if(item.count<1){
          item.count=1
        }    
      }
      return item
    })
    jihe();
    },
    jia(state,id){
      state.cartlist=state.cartlist.map(item=>{
        if(id===item.classifyId){
          item.count++ 
        }
        return item
      })
      jihe();  
      },
     islogin(state,login){
      state.user.username=login
      state.user.islogin=true
     },
     outlogin(state){
      state.user.islogin=false 
     } 
  },
  getters:{
  zong(){
    return state.amount
  }
  },
  plugins: [myPlugin]
})




export default store;